﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using log4net;
using TestWebApplication.Models;

namespace TestWebApplication
{
    // Примечание: Инструкции по включению классического режима IIS6 или IIS7 
    // см. по ссылке http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly ILog LOGGER = LogManager.GetLogger(typeof(MvcApplication));

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Имя маршрута
                "{controller}/{action}/{id}", // URL-адрес с параметрами
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Параметры по умолчанию
            );

        }

        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();
            LOGGER.Info("Starting application...");

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            var container = ContainerFactory.Create();
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));

            LOGGER.Info("Application started");
        }

        protected void Application_End(object sender, EventArgs e)
        {
            LOGGER.Info("Stop application");
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            var ex = Server.GetLastError();
            Server.ClearError();

            if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
            {
                LOGGER.Error("Страница не найдена: " + Request.RawUrl);
                Response.RedirectToRoute(
                    new
                    {
                        controller = "Error",
                        action = "NotFound",
                        path = Request.RawUrl
                    });
                return;
            }
            
            LOGGER.Fatal(ex.ToString());
            Response.RedirectToRoute(
                    new
                    {
                        controller = "Error",
                        action = "Internal"
                    });
        }

    }
}